package com.example.skillcinema.ui.screens.main

import android.os.Build
import android.os.Build.VERSION
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.skillcinema.R
import com.example.skillcinema.adapters.FilmAllPagedAdapter
import com.example.skillcinema.adapters.FilmRecyclerViewAdapter
import com.example.skillcinema.adapters.FootLoadStateAdapter
import com.example.skillcinema.databinding.FragmentFilmAllBinding
import com.example.skillcinema.db.enums.FilmFetchType
import com.example.skillcinema.ui.screens.main.viewmodels.FilmAllViewModel
import com.example.skillcinema.utils.sharemodels.FilmDataToShare
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch

@AndroidEntryPoint
class FilmAllFragment : Fragment() {
    private var filmData: FilmDataToShare? = null
    private var _binding: FragmentFilmAllBinding? = null
    private val binding: FragmentFilmAllBinding
        get() = _binding!!

    private val viewModel: FilmAllViewModel by viewModels<FilmAllViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            filmData = if (VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                it.getParcelable(FILM_FETCH_TYPE_ARG, FilmDataToShare::class.java)
            } else {
                it.getParcelable<FilmDataToShare>(FILM_FETCH_TYPE_ARG)
            }
            viewModel.fetchType = filmData?.fetchType!!
            viewModel.filmId = filmData?.id ?: 0
            if (filmData?.filters != null) {
                viewModel.filters = filmData?.filters!!
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentFilmAllBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        (activity as? AppCompatActivity)?.setSupportActionBar(binding.toolbar)
        (activity as? AppCompatActivity)?.supportActionBar?.setDisplayHomeAsUpEnabled(true)
        (activity as? AppCompatActivity)?.supportActionBar?.setDisplayShowTitleEnabled(false)
        binding.toolbar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }
        binding.toolbarTitle.text = filmData?.title
        val adapter: FilmAllPagedAdapter = FilmAllPagedAdapter({ id -> onFilmClicked(id) })
        viewModel.loadIt()
        binding.swipeRefresh.setOnRefreshListener {
            adapter.refresh()
        }
        adapter.loadStateFlow.onEach {
            binding.swipeRefresh.isRefreshing = it.refresh == LoadState.Loading
        }.launchIn(viewLifecycleOwner.lifecycleScope)
        lifecycleScope.launch {
            try {
                viewModel.filmPaged.onEach {
                    adapter.submitData(it)
                }.launchIn(viewLifecycleOwner.lifecycleScope)
            } catch (ex: Exception) {
                Log.e("API_ERROR", "Error fetching photos: ${ex.message}")
            }
        }
        binding.allFilmCollectionRecyclerView.adapter = adapter.withLoadStateFooter(
            FootLoadStateAdapter()
        )
    }

    fun onFilmClicked(id: Int) {
        val bundle: Bundle = Bundle().apply {
            putInt(FilmDetailsFragment.FILM_ID_ARG, id)
        }
        findNavController().navigate(R.id.action_filmAllFragment_to_filmDetailsFragment, bundle)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: FilmDataToShare) =
            FilmAllFragment().apply {
                arguments = Bundle().apply {
                    putParcelable(FILM_FETCH_TYPE_ARG, param1)
                }
            }

        const val FILM_FETCH_TYPE_ARG = "film_type_fetch"
        const val FILM_COUNTRY_ID_ARG = "film_country_id"
        const val FILM_GENRE_ID_ARG = "film_genre_id"
        const val FILM_TITLE_ARG = "film_title"
    }
}